package com.jfok.server.service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jfok.server.DAO.SystemBaseDAO;
import com.jfok.shared.TreeNodeRecordChecked;
import com.jfok.shared.service.IUserService;
import com.jfok.server.hibernate.systemset._FieldReadonlyRole;
import com.jfok.server.hibernate.systemset._FieldRole;
import com.jfok.server.hibernate.systemset._Role;
import com.jfok.server.hibernate.systemset._RoleGroup;
import com.jfok.server.hibernate.systemset._User;
import com.jfok.server.hibernate.systemset._UserFieldReadonlyRole;
import com.jfok.server.hibernate.systemset._UserFieldRole;
import com.jfok.server.hibernate.systemset._UserRole;
import com.jfok.server.login.SessionManage;
import com.jfok.server.login.UserSession;
import sun.misc.BASE64Encoder;

@Service
public class UserService implements IUserService {

	private static final Log log = LogFactory.getLog(UserService.class);

	@Resource
	private SystemBaseDAO systemBaseDAO;

	public void userLogined(UserSession userSession, HttpServletRequest request) {
		// 用户登录后的初始化工作

		log.debug("用户登录成功，即将进行登录后的初始化操作！");

	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public List<TreeNodeRecordChecked> getFieldRolesWithEmployeeId(Integer userId) {

		List<_UserFieldRole> userFieldRoles = (List<_UserFieldRole>) systemBaseDAO.findByProperty(
				_UserFieldRole.class, "tf_userId", (userId));
		TreeNodeRecordChecked root = new TreeNodeRecordChecked(null, null, "所有隐藏字段角色", null, null,
				null, null);
		root.setLeaf(false);
		List<_FieldRole> groups = (List<_FieldRole>) systemBaseDAO.findAll(_FieldRole.class);
		Boolean rootChecked = true;

		for (_FieldRole role : groups) {
			TreeNodeRecordChecked roleRecord = new TreeNodeRecordChecked(null, null, role.getTf_name(),
					null, role.getTf_fieldRoleId(), null, null);
			for (_UserFieldRole userRole : userFieldRoles) {
				if (userRole.getTf_fieldRoleId().equals(role.getTf_fieldRoleId())) {
					roleRecord.setChecked(true);
					break;
				}
			}
			roleRecord.setTag(1);
			rootChecked = rootChecked && roleRecord.getChecked();
			root.getChildren().add(roleRecord);
		}
		root.setChecked(rootChecked);
		List<TreeNodeRecordChecked> result = new ArrayList<TreeNodeRecordChecked>();
		result.add(root);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean setFieldRolesWithEmployeeId(Integer userId, String noderecords) {
		List<_UserFieldRole> userRoles = (List<_UserFieldRole>) systemBaseDAO.findByProperty(
				_UserFieldRole.class, "tf_userId", userId);
		for (int i = userRoles.size() - 1; i >= 0; i--) {
			systemBaseDAO.delete(userRoles.get(i));
		}
		if (noderecords != null && noderecords.length() > 0) {
			String roles[] = noderecords.split(",");
			for (String role : roles)
				systemBaseDAO.save(new _UserFieldRole(role, userId));
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public List<TreeNodeRecordChecked> getFieldReadonlyRolesWithEmployeeId(Integer userId) {

		List<_UserFieldReadonlyRole> userFieldRoles = (List<_UserFieldReadonlyRole>) systemBaseDAO
				.findByProperty(_UserFieldReadonlyRole.class, "tf_userId", (userId));
		TreeNodeRecordChecked root = new TreeNodeRecordChecked(null, null, "所有只读字段角色", null, null,
				null, null);
		root.setLeaf(false);
		List<_FieldReadonlyRole> groups = (List<_FieldReadonlyRole>) systemBaseDAO
				.findAll(_FieldReadonlyRole.class);
		Boolean rootChecked = true;

		for (_FieldReadonlyRole role : groups) {
			TreeNodeRecordChecked roleRecord = new TreeNodeRecordChecked(null, null, role.getTf_name(),
					null, role.getTf_fieldRoleId(), null, null);
			for (_UserFieldReadonlyRole userRole : userFieldRoles) {
				if (userRole.getTf_fieldRoleId().equals(role.getTf_fieldRoleId())) {
					roleRecord.setChecked(true);
					break;
				}
			}
			roleRecord.setTag(1);
			rootChecked = rootChecked && roleRecord.getChecked();
			root.getChildren().add(roleRecord);
		}
		root.setChecked(rootChecked);
		List<TreeNodeRecordChecked> result = new ArrayList<TreeNodeRecordChecked>();
		result.add(root);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean setFieldReadonlyRolesWithEmployeeId(Integer userId, String noderecords) {
		List<_UserFieldReadonlyRole> userRoles = (List<_UserFieldReadonlyRole>) systemBaseDAO
				.findByProperty(_UserFieldReadonlyRole.class, "tf_userId", userId);
		for (int i = userRoles.size() - 1; i >= 0; i--) {
			systemBaseDAO.delete(userRoles.get(i));
		}
		systemBaseDAO.getHibernateTemplate().flush();
		if (noderecords != null && noderecords.length() > 0) {
			String roles[] = noderecords.split(",");
			for (String role : roles)
				systemBaseDAO.save(new _UserFieldReadonlyRole(role, userId));
		}
		return true;
	}
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public List<TreeNodeRecordChecked> getRolesWithEmployeeId(Integer userId) {

		List<_UserRole> userRoles = (List<_UserRole>) systemBaseDAO.findByProperty(_UserRole.class,
				"tf_User.tf_userId", (userId));

		TreeNodeRecordChecked root = new TreeNodeRecordChecked(null, null, "所有角色", null, null, null,
				null);
		root.setLeaf(false);
		List<_RoleGroup> groups = (List<_RoleGroup>) systemBaseDAO.findAll(_RoleGroup.class);
		Boolean rootChecked = true;
		for (_RoleGroup group : groups) {
			List<_Role> roles1 = (List<_Role>) systemBaseDAO.findByPropertyAllSort(_Role.class,
					"tf_roleId", "asc", "tf_RoleGroup.tf_roleGroupId", group.getTf_roleGroupId(), null, null);
			if (roles1.size() > 0) {
				TreeNodeRecordChecked groupRecord = new TreeNodeRecordChecked(null, null,
						group.getTf_title(), null, null, null, null);
				groupRecord.setLeaf(false);
				root.getChildren().add(groupRecord);
				boolean groupChecked = true;
				for (_Role role : roles1) {
					TreeNodeRecordChecked roleRecord = new TreeNodeRecordChecked(null, null,
							role.getTf_roleName(), null, role.getTf_roleId(), null, null);
					for (_UserRole userRole : userRoles) {
						if (userRole.getTf_Role().getTf_roleId().equals(role.getTf_roleId())) {
							roleRecord.setChecked(true);
							break;
						}
					}
					roleRecord.setTag(1);
					groupChecked = groupChecked && roleRecord.getChecked();
					groupRecord.getChildren().add(roleRecord);
				}
				groupRecord.setChecked(groupChecked);
				rootChecked = rootChecked && groupRecord.getChecked();
			}
		}
		root.setChecked(rootChecked);
		List<TreeNodeRecordChecked> result = new ArrayList<TreeNodeRecordChecked>();
		result.add(root);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean setRolesWithEmployeeId(Integer userId, String noderecords) {
		List<_UserRole> userRoles = (List<_UserRole>) systemBaseDAO.findByProperty(_UserRole.class,
				"tf_User.tf_userId", userId);
		for (int i = userRoles.size() - 1; i >= 0; i--) {
			systemBaseDAO.delete(userRoles.get(i));
		}
		if (noderecords != null && noderecords.length() > 0) {
			String roles[] = noderecords.split(",");
			for (String role : roles)
				systemBaseDAO.save(new _UserRole(new _Role(role), new _User(userId)));
		}
		return true;
	}

	
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean resetPassword(Integer userId) {
		_User user = (_User) systemBaseDAO.findById(_User.class, userId);
		user.setTf_password(fu_GenPasswordWithId(userId, "123456"));
		systemBaseDAO.attachDirty(user, null);
		return true;

	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean changePassword(String oldPassword, String newPassword, HttpServletRequest request) {
		UserSession userSession = SessionManage.getInstance().getUserSession(request.getSession());
		_User user = (_User) systemBaseDAO.findById(_User.class, userSession.getUserId());
		if (user.getTf_password().equals(fu_GenPasswordWithId(user.getTf_userId(), oldPassword))) {
			user.setTf_password(fu_GenPasswordWithId(user.getTf_userId(), newPassword));
			systemBaseDAO.attachDirty(user, null);
			return true;
		} else
			return false;
	}

	
	public static String EncoderByMd5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		BASE64Encoder base64en = new BASE64Encoder();
		String newstr = null;
		try {
			newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return newstr;
	}

	
	public static String fu_GenPasswordWithId(Integer id, String p) {
		return EncoderByMd5(id.toString() + " " + p);
	}

}
